<template>
  <div class="role-add">
    <div class="page-header">
      <h2>添加角色</h2>
      <p>创建新的系统角色</p>
    </div>

    <div class="add-form-container">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="120px"
        class="role-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input
                v-model="roleForm.name"
                placeholder="请输入角色名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色状态" prop="isActive">
              <el-radio-group v-model="roleForm.isActive">
                <el-radio :value="true">启用</el-radio>
                <el-radio :value="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>

        <el-form-item label="菜单权限" prop="menus">
          <div class="permission-tree">
            <el-tree
              ref="menuTreeRef"
              :data="menuList"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-expand-all="true"
              :check-strictly="false"
              @check="handleMenuCheck"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            创建角色
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useRoleStore } from '@/stores/role'
import { useMenuStore } from '@/stores/menu'
const router = useRouter()
const roleFormRef = ref()
const menuTreeRef = ref()
const loading = ref(false)
const useStore =useRoleStore()
// 菜单列表--->需要从数据库获取
const menuList = ref([])
const menuStore =useMenuStore()
// 树形控件属性
const treeProps = {
  children: 'children',
  label: 'name'
}

// 表单数据
const roleForm = reactive({
  name: '',
  description: '',
  isActive: true,
  menuIds: []
})

// 验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 方法
const loadMenus = async () => {
  try {
    // 模拟API调用获取菜单列表
    const res = await menuStore.getmenutree()
    menuList.value=res
    console.log('菜单列表加载完成')
  } catch (error) {
    ElMessage.error('加载菜单列表失败')
  }
}
const handleMenuCheck = (data, checked) => {
  // 获取选中的菜单ID
  const checkedKeys = menuTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
  roleForm.menuIds = [...checkedKeys, ...halfCheckedKeys]
}

const handleSubmit = async () => {
  try {
    // 表单验证
    await roleFormRef.value.validate()
    
    // 检查是否选择了菜单权限
    if (roleForm.menuIds.length === 0) {
      ElMessage.warning('请至少选择一个菜单权限')
      return
    }
    
    loading.value = true
    const res =await useStore.addRole(roleForm)
    ElMessage.success('角色创建成功')
    
    // 跳转到角色列表
    router.push('/roles/list')
    
  } catch (error) {
    if (error) {
      ElMessage.error('请检查表单输入')
    }
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  roleFormRef.value.resetFields()
  menuTreeRef.value.setCheckedKeys([])
  roleForm.menuIds = []
}

const handleCancel = () => {
  router.push('/roles/list')
}

// 生命周期
onMounted(() => {
  loadMenus()
})
</script>

<style scoped>
.role-add {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 5px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.add-form-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.role-form {
  max-width: 800px;
}

.permission-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  background: #fafafa;
  max-height: 300px;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-tree) {
  background: transparent;
}

:deep(.el-tree-node__content) {
  height: 32px;
}
</style>
